package com.googlecode.mailnet.netmodel;

import java.util.Map;
import java.util.HashMap;

/**
 * Base class for all network model entities.
 *
 * @author Iskander Akishev
 */
abstract class NetworkItem {

	// todo: javadocs

	final NetworkConfiguration networkConfiguration;
	private boolean isRemoved;
	private String name;

	NetworkItem(NetworkConfiguration networkConfiguration) {
		if (networkConfiguration == null) {
			throw new NullPointerException();
		}
		this.networkConfiguration = networkConfiguration;
		generateDefaultName();
	}

	private static final Map<Class<? extends NetworkItem>, Integer> NUMERATOR =
		new HashMap<Class<? extends NetworkItem>, Integer>();
	
	private void generateDefaultName() {
		Class<? extends NetworkItem> clazz = getClass();
		Integer number = NUMERATOR.get(clazz);
		if (number == null) {
			number = 0;
		}
		name = clazz.getSimpleName() + (++number);
		NUMERATOR.put(clazz, number);
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		if (name == null) {
			throw new NullPointerException("Name is null");
		}
		checkBeforeModifications();
		this.name = name;
	}

	protected final void checkBeforeModifications() throws IllegalStateException {
		networkConfiguration.checkBeforeModifications();
		if (isRemoved) {
			throw new IllegalStateException(getClass().getSimpleName() + " is already removed.");
		}
	}

	protected final boolean markRemoved() throws IllegalStateException {
		networkConfiguration.checkBeforeModifications();
		boolean wasRemoved = isRemoved;
		isRemoved = true;
		return wasRemoved;
	}

	public final boolean isRemoved() {
		return isRemoved;
	}

	public abstract void remove();

	abstract void validate() throws IllegalStateException;

	@Override
	public String toString() {
		return name;
	}
}
